//
//  QianliUserOrderlistVC.swift
//  todoios
//
//  Created by qianli on 2025/4/21.
//

import Foundation
import UIKit

class QianliUserOrderlistVC: QianliParentNaviVC {
    private var lBRorfbo6yFDAbBu:[OrdersModel]=[]
    private var _iPageNum:Int = 1
    private var _iPageTotal:Int = 1
    private var sBbMmqY5sprgO6Lj:Bool = false
    private var yDCfMxMjoZSqnqxo:RetryNet?
    private var YSgwxXklgw9hk52r:MBProgressHUD?
    
    private var I4LIMbAS6nkCuNER = UIRefreshControl()
    private var _isLoadingMore = false
    private let RF7NlUOk3CS8x58m = UILabel()
    private let brzwDc3ZHa8Rmucg = UIActivityIndicatorView(style: .medium)
    
//    private var RmDfowa8fqNCMjFK:Int = 0
//    private var u6GDB3XSEFJ3CxcX:Int = 0
    
    lazy var orderTable: UITableView = {
        let table = UITableView()
        return table
    }()
    
    deinit {
        QianliUniversalFunc.QianliLog("------QianliUserOrderlistVC.deinit")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func aB7kFqI8MB6DRPQC() {
        if(!self.sBbMmqY5sprgO6Lj){
            self.I7rqmvOgyFeY3vxV()
        }
    }
    
    override func GHL4Rhb91XYBer27() {
        self.zdMpsGrNncVEHdYA(title: LocalizedString("Order List"))//"订单列表"
        
        view.addSubview(self.orderTable)
        orderTable.frame = CGRect(x: 0, y: topSpace+15, width: qianli_pm_width, height: qianli_pm_height - topSpace - 15)
        orderTable.delegate = self
        orderTable.dataSource = self
//        nodeTable.separatorStyle = .singleLine //默认即为singleLine
        orderTable.separatorStyle = .none
        orderTable.register(OrderItemCell.self, forCellReuseIdentifier: "OrderItemCell")
        orderTable.backgroundColor = .secondarySystemBackground
        // 设置下拉刷新
        self.I4LIMbAS6nkCuNER.addTarget(self, action: #selector(Mi98Ng5kg6iUVKk0), for: .valueChanged)
        orderTable.refreshControl = self.I4LIMbAS6nkCuNER
        gZk5cuoJMRAV2npo()
    }
    
    override func clFi25NuDNbscWXL() {
        self.l0JOXR3PG9RznwqZ()
        self.h3wqTp4QEDNi67J0()
        super.clFi25NuDNbscWXL()
    }
    
    func h3wqTp4QEDNi67J0(){
        if let retryview =  self.yDCfMxMjoZSqnqxo{
            for childview in retryview.subviews{
                childview.removeFromSuperview()
            }
            retryview.removeFromSuperview()
        }
        self.yDCfMxMjoZSqnqxo = nil
    }
    
    func dnOwhBpbw9jbgRH7(){
        let topSpace = UIDevice.qianli_statusbar_and_navibar_height()
        if(self.yDCfMxMjoZSqnqxo == nil){
            self.yDCfMxMjoZSqnqxo = RetryNet(frame: CGRect(x: 0, y: topSpace+5.0, width: qianli_pm_width, height: qianli_pm_height-topSpace-5.0))
            if let retryview = self.yDCfMxMjoZSqnqxo{
                self.view.addSubview(retryview)
                retryview.tapBlock = { [weak self] in
                    self?.I7rqmvOgyFeY3vxV()
                }
            }
        }
    }
    
    // 设置上拉加载更多的 footer
    private func gZk5cuoJMRAV2npo() {
        let footer = UIView(frame: CGRect(x: 0, y: 0, width: orderTable.bounds.width, height: 50))
        self.RF7NlUOk3CS8x58m.text = _iPageNum>=_iPageTotal ? "- \(LocalizedString("No More")) -" : LocalizedString("Pull up to load more")
        self.RF7NlUOk3CS8x58m.textAlignment = .center
        self.RF7NlUOk3CS8x58m.textColor = .secondaryLabel
        self.RF7NlUOk3CS8x58m.frame = CGRect(x: footer.bounds.width/2 - 100, y: 20, width: 200, height: 30)
        footer.addSubview(self.RF7NlUOk3CS8x58m)
        self.RF7NlUOk3CS8x58m.isHidden = true

        self.brzwDc3ZHa8Rmucg.frame = CGRect(x: footer.bounds.width/2 - 30/2 - 70, y: 20, width: 30, height: 30)
        footer.addSubview(self.brzwDc3ZHa8Rmucg)
        self.brzwDc3ZHa8Rmucg.color = .label
        orderTable.tableFooterView = footer
    }
    
    @objc func I7rqmvOgyFeY3vxV(){
        self.sBbMmqY5sprgO6Lj = true
        self.M62h1bVOydwY8i4y(LocalizedString("Loading, please wait..."))//"正在加载,请稍候..."
//        Moya本身有缓存功能，首次取得数据后，再次进来执行readyVipInfo，数据会马上得到
        VipViewModel.shared.ouraS2LUid0tda1u(pagination: Pagination(orderBy: "id DESC", pageNum: _iPageNum, pageSize: 50))
        VipViewModel.shared.completionHandler = {(result) in
            DispatchQueue.main.async {[weak self] in
                if let self = self{
                    self.I4LIMbAS6nkCuNER.endRefreshing()
                    self.l0JOXR3PG9RznwqZ()
                    self.EBJjUBJG5MEiaoMF(result)
                }
            }
        }
    }
    
    @objc func Mi98Ng5kg6iUVKk0(){
        self.sBbMmqY5sprgO6Lj = true
        _iPageNum = 1 //下拉即为拉取最新的数据
        VipViewModel.shared.ouraS2LUid0tda1u(pagination: Pagination(orderBy: "id DESC", pageNum: _iPageNum, pageSize: 50))
        VipViewModel.shared.completionHandler = {[weak self](result) in
            DispatchQueue.main.async {
                if let self = self{
                    self.I4LIMbAS6nkCuNER.endRefreshing()
                    self.EBJjUBJG5MEiaoMF(result)
                }
            }
        }
    }
    
    // 上拉加载更多的动作
    private func WiolLzCiaV0Lkpz0() {
        if (_iPageNum>=_iPageTotal){
            _isLoadingMore = false
            self.RF7NlUOk3CS8x58m.text = "- \(LocalizedString("No More")) -"
            return
        }
        _iPageNum += 1
        guard !_isLoadingMore else { return }
        _isLoadingMore = true
        self.RF7NlUOk3CS8x58m.text = LocalizedString("Loading...") //"正在加载..."
        self.brzwDc3ZHa8Rmucg.startAnimating()

        // 模拟加载更多数据
        DispatchQueue.global().async {
            sleep(2)
            DispatchQueue.main.async {
                self._isLoadingMore = false
                self.RF7NlUOk3CS8x58m.text = LocalizedString("Pull up to load more")
                self.brzwDc3ZHa8Rmucg.stopAnimating()
                // 这里可以添加加载更多数据的逻辑
                
            }
        }
    }
    
    func EBJjUBJG5MEiaoMF(_ result:String){
        if(result.isEmpty){
            if let orderData = VipViewModel.shared.orderData{
                if (orderData.total>0){
                    if let myOrderList = orderData.data{
                        self.lBRorfbo6yFDAbBu = myOrderList
                        if(self.lBRorfbo6yFDAbBu.count>0){
                            self.RF7NlUOk3CS8x58m.isHidden = false
                        }
                        self.orderTable.reloadData()
                        self.h3wqTp4QEDNi67J0()
                        return
                    }
                }
            }
//数据为空
            dnOwhBpbw9jbgRH7()
            if let retryview = self.yDCfMxMjoZSqnqxo{
                retryview.vSXenwySp9gyesbp(LocalizedString("Order Data is Null"))//"当前还没有订单数据"
                retryview.d770kqK5BHcHWehm(1)
            }
        }else{
//读取失败，retry
            self.RF7NlUOk3CS8x58m.isHidden = true
            let hud = MBProgressHUD.showAdded(to: view, animated: true)
            hud.mode = .text
            hud.label.text = result
            hud.hide(animated: true, afterDelay: 1.0) // 2 秒后自动消失
            
            dnOwhBpbw9jbgRH7()
            if let retryview = self.yDCfMxMjoZSqnqxo{
                retryview.vSXenwySp9gyesbp(LocalizedString("Load Failed. Please check network & try again!"))
                retryview.d770kqK5BHcHWehm(0)
            }
        }
        
        self.orderTable.reloadData()
    }
    
}

extension QianliUserOrderlistVC{
    func ARf8b82n5EiZgFrO(_ msg:String){
        DispatchQueue.main.async {[weak self] in
            if let self = self{
                self.l0JOXR3PG9RznwqZ()
                 
                self.YSgwxXklgw9hk52r = MBProgressHUD.showAdded(to: self.view, animated: true)
                if let loadingHud = self.YSgwxXklgw9hk52r,!msg.isEmpty{
                    loadingHud.label.text = msg
                }
            }
        }
    }
    
    private func dUlkSTiYVxtSnxz7(){
        if let loadingHud = self.YSgwxXklgw9hk52r{
            loadingHud.hide(animated: true)
        }
        self.YSgwxXklgw9hk52r = nil
    }
    
    func OwfN0pY84aBgeJjP(_ string: String) -> String {
        let allowedCharacters = CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted
        return string.addingPercentEncoding(withAllowedCharacters: allowedCharacters) ?? string
    }
    
}

extension QianliUserOrderlistVC:UITableViewDelegate, UITableViewDataSource{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y
        let contentHeight = scrollView.contentSize.height
        let height = scrollView.frame.height

        if offsetY > contentHeight - height {
            WiolLzCiaV0Lkpz0()
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.lBRorfbo6yFDAbBu.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "OrderItemCell") as? OrderItemCell//从缓存池中取
        if nil == cell{
            cell = UITableViewCell.init(style: .default, reuseIdentifier: "OrderItemCell") as? OrderItemCell
        }
        
        cell!.Qianli_UpdateInfo(info: self.lBRorfbo6yFDAbBu[indexPath.row])
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 110.0
    }
}
